package com.boarsoft.boar.config.var.biz;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.config.entity.ConfigVarEnv;
import com.boarsoft.boar.config.var.ConfigVarEnvBiz;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

import javax.persistence.PersistenceException;

@Component("configVarEnvBiz")
public class ConfigVarEnvBizImpl extends SimpleBizImpl implements ConfigVarEnvBiz {

	@Override
	@Transactional(readOnly = true)
	public ConfigVarEnv get(String id) {
		return dao.get(ConfigVarEnv.class, id);
	}

	@Override
	@Transactional
	public String add(ConfigVarEnv a) {
		ConfigVarEnv cv = find(a.getVarId(),a.getEnv());
		if(cv != null) {
			cv.setValue(a.getValue());
			dao.update(cv);
			a.setId(cv.getId());
		}else {
			dao.save(a);
		}
		return a.getId();
	}

	@Override
	@Transactional
	public void batchInsert(List<ConfigVarEnv> configVarEnvList) {
		try {
			dao.batchSave(configVarEnvList, 100);
		}catch (PersistenceException e){
			throw new RuntimeException("操作失败：记录重复");
		}
	}

	@Override
	@Transactional(readOnly = true)
	public ConfigVarEnv find(String varId,String env) {
		return dao.find(ConfigVarEnv.class, String.format("and varId = '%s' and env = '%s'", varId, env));
	}

	@Override
	@Transactional
	public void delete(String id) {
		dao.delete(ConfigVarEnv.class, id);
	}

	@Override
	@Transactional
	public List<ConfigVarEnv> list(String varId) {
		StringBuffer sb = new StringBuffer("select r from ")//
				.append(ConfigVarEnv.class.getName())//
				.append(" r where r.varId = :varId");
		Query<ConfigVarEnv> q = dao.createQuery(ConfigVarEnv.class, sb.toString());
		q.setParameter("varId", varId);
		return q.getResultList();
	}

	@Override
	@Transactional(readOnly = true)
	public List<ConfigVarEnv> findByEnv(String appId, String env) {
		String sql="select e.* from config_var_env e where e.vEnv='"+env+"'";
		if(appId != null){
			sql = "select e.* from config_var_env e where e.cVarId "
					+ "in (select a.cVarId from config_var_app a where a.cAppId='"+appId+"')";
		}
		return dao.listBySQL(sql, ConfigVarEnv.class);
	}

	@Override
	@Transactional
	public void update(ConfigVarEnv a) {
		dao.update(a);
	}

}